package com.zxy.servlet;

import jakarta.servlet.*;
import jakarta.servlet.annotation.WebInitParam;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;

import java.io.IOException;
import java.util.Enumeration;
@WebServlet(
        urlPatterns = "/servlet",
        initParams = {@WebInitParam(name="keya",value = "value"),@WebInitParam(name="keyb",value = "valub")}
)
public class Servlet extends HttpServlet {
    @Override
    public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
        ServletConfig servletConfig = getServletConfig();
//        获取初始配置信息
//        根据参数名获取参数值
        String keya = servletConfig.getInitParameter("keya");
        System.out.println("keya="+keya);
//        获取所有的初始参数的名字
//        hasMoreElements 判断有没有下一个参数如果有返回true
//        nextElement 取出下一个元素 向下移动
        Enumeration<String> initParameter = servletConfig.getInitParameterNames();

        while (initParameter.hasMoreElements()) {
            String pname = initParameter.nextElement();
            System.out.println(pname+"="+getInitParameter(pname));


        }
        System.out.println("------------------ServletContext获取参数-----------------------");
        ServletContext servletContext1 = getServletContext();
        ServletContext servletContext2 = servletConfig.getServletContext();
        ServletContext servletContext3 = req.getServletContext();
        System.out.println(servletContext1 == servletContext2);
        System.out.println(servletContext2 == servletContext3);

        String encoding = servletContext1.getInitParameter("encoding");
        System.out.println("encoding"+encoding);
        Enumeration<String> parameterNames = servletContext1.getInitParameterNames();
        while(parameterNames.hasMoreElements()){
            String pname= parameterNames.nextElement();
            System.out.println(pname+"="+servletContext1.getInitParameter(pname));
        }
//        放入数据到域对象中
        servletContext1.setAttribute("ka","va");
//        在域对象中修改数据
//        servletContext1.setAttribute("ka","vaa");
//        在域对象获取数据
//        String ka =(String)servletContext1.getAttribute("ka");
//        从域对象中移除数据
        servletContext1.removeAttribute("ka");

    }
}
